package com.polight.dao.impl;


import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.polight.dao.User;

public class UserDaoImpl {
	
	private SessionFactory sf = null;
	
	public void init() {
		Configuration cfg = new Configuration();
		sf = cfg.configure().buildSessionFactory();
	}
	
	public void destroy() {
		Session session = sf.openSession();
		session.close();
		sf.close();
	}

	public void addUser(User user) {
		Session session = sf.openSession();
		session.beginTransaction();
		session.save(user);
		session.getTransaction().commit();
	}

	public User findUser(User user) {
		return findUser(user.getName());
	}
	
	public User findUser(String name) {
		Session session = sf.openSession();
		List<User> list = (List<User>)(session.createQuery("from User as user where user.name = ?")
				.setString(0, name)
				.list());
		
		return list.get(0);
	}
	
	public void delUser(User user) {
		Session session = sf.openSession();
		session.delete(user);
		session.getTransaction().commit();
	}
	
	public void updateUser(User user) {
		Session session = sf.openSession();
		session.update(user);
		session.getTransaction().commit();
	}
}
